########################################
#### figure_5.R: Generates Figure 5 ####
########################################

q6 <- read.csv(here("Data","midterm_fraud_open_ends6.csv"), stringsAsFactors=FALSE)
q6<-q6[,c(1,3)]
df <-merge(dta_midterm,q6)

df$w9_2022_1_elections6_code[df$w9_2022_1_elections6_code=="99"] <-7
results <- pollster::moe_crosstab(df, y=w9_2022_1_elections6_code, x=pid, weight=weight) %>%
  mutate(upper = pct+moe) %>%
  mutate(lower = pct-moe) %>%
  mutate(wn = round(n*(pct/100),0))

results$w9_2022_1_elections6_code <- recode(results$w9_2022_1_elections6_code, 
                                            '1' = "Logical deduction",
                                            '21' = "Takes too long to count votes",
                                            '22' = "Ballot harvesting/Mail",
                                            '23' = "Voting machine problems",
                                            '24' = "Voting procedure conspiracy",
                                            '3' = "Democrats winning",
                                            '4' = "The Media",
                                            '5' = "Convictions",
                                            '6' = "Gerrymandering",
                                            '7'	= "No evidence offered")

results$q=1
results$w9_2022_1_elections6_code = as.factor(results$w9_2022_1_elections6_code)

results<- results %>% 
  arrange(pct)

fig_5 = results  %>% mutate(pid = as.factor(pid),
                    level = tidytext::reorder_within(w9_2022_1_elections6_code, pct, pid)) %>%
  ggplot(aes(x=level, y= pct, color=pid)) +
  geom_point(aes(y = pct), position = position_dodge()) +
  geom_errorbar(aes(ymin=lower, ymax=upper), width=0, position=position_dodge(.9)) +
  geom_text(aes(y= pct,label = paste(round(pct,1),"%",sep="")), fontface = "bold", vjust = 1.5,
            position = position_dodge(1), size = 4) +
  xlab("") +
  scale_y_continuous(limits = c(-10,50), name = "Percent",breaks = seq(0,100,50), labels = paste0(seq(0,100,50),"%")) +
  coord_flip() +
  tidytext::scale_x_reordered() +
  facet_wrap(~pid, scales = "free_y") +
  
  scale_color_manual(values=c("Republican" = "#D50A0A","Democrat" ="#013369", "Independent"="#999999")) +
  guides(fill="none", color="none") +
  ggtitle(wrapper("",50)) +
  theme_prl()+
  guides(fill=guide_legend(title="",reverse = TRUE, byrow=TRUE)) +
  theme(panel.grid.major = element_blank(), legend.position = "none") +
  labs(caption = "Weighted values and 95% CIs") 

ggsave(here("Figures","figure_5.pdf"), fig_5 , 
       dpi = 600, units = "in", width=10, height=5)
